package com.yzt.zhuju.activity;

import android.annotation.TargetApi;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.ValueCallback;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSONObject;
import com.yzt.zhuju.MainMenuContsant;
import com.yzt.zhuju.RXingUtils;
import com.yzt.zhuju.arouter.RouterMain;
import com.yzt.zhuju.arouter.RouterMine;
import com.yzt.zhuju.arouter.RouterUser;
import com.yzt.zhuju.base.BaseWebViewActivity;
import com.yzt.zhuju.event.RxBus;
import com.yzt.zhuju.event.main.MainSwitchPageEvent;
import com.yzt.zhuju.event.web.WebRouterEvent;
import com.yzt.zhuju.network.HttpUrlManager;
import com.yzt.zhuju.utils.EncodeUtils;
import com.yzt.zhuju.utils.ViewUtils;
import com.yzt.zhuju.webview.AppWebChromeClient;
import com.yzt.zhuju.webview.AppWebViewClient;
import com.yzt.p_base.BuildConfig;
import com.yzt.p_base.utils.NetworkUtils;
import com.yzt.p_base.utils.StringUtils;
import com.yzt.p_base.utils.ToastUtil;
import com.yzt.zhuju.utils.UrlUtil;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;

/**
 * author : bob
 * date   : 2022/12/9
 * desc   :
 */
@Route(path = RouterMain.ACTIVITY_APP_WEB_VIEW)
public class AppWebViewActivity extends BaseWebViewActivity {

    private static final String TAG = AppWebViewActivity.class.getSimpleName();

    private String mUrl;

    private String mHeadGson;

    private ValueCallback<Uri[]> mUploadCallbackAboveL;

    private ValueCallback<Uri> mUploadMessage;

    @Override
    protected void onDestroy() {
        mWebView.clearCache(true);
        mWebView = null;
        super.onDestroy();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        updateStatusBarHeight();
        observerRxBus(WebRouterEvent.class, event -> openNewPage(event.getEventName(), event.getJson()));

        mWebView.setWebChromeClient(new AppWebChromeClient(this, new AppWebChromeClient.OnWebChromeListener() {
            @Override
            public void onOpenFileChooser(ValueCallback<Uri> uploadMsg) {
                mUploadMessage = uploadMsg;
            }

            @Override
            public void onShowFileChooser(ValueCallback<Uri[]> filePathCallback) {
                mUploadCallbackAboveL = filePathCallback;
            }
        }));
    }

    @Override
    public void installViews() {
        if (getIntent().getExtras() != null) {
            mUrl = getIntent().getExtras().getString("mUrl");
        }
        if (BuildConfig.DEBUG) {
            Log.e(TAG, "访问的网页为:" + mUrl);
        }
        if (!TextUtils.isEmpty(mUrl)) {
            String hostStr = HttpUrlManager.getAppHttpUrl();

            //处理url，由于配置中有些链接没有配置host，需要加上
            if (!(mUrl.startsWith("file://") || mUrl.startsWith("http://") || mUrl.startsWith("https://"))) {

                mUrl = mUrl.replaceAll("//", "/");

                if (hostStr.endsWith("/")) {
                    mUrl = hostStr + mUrl;
                } else {
                    mUrl = hostStr + File.separator + mUrl;
                }
            }

            mHeadGson = getIntent().getExtras().getString("mHeadGson");

            if (NetworkUtils.isWifiProxy() && !BuildConfig.DEBUG) {
                mUrl = NetworkUtils.NETWORK_PROXY_PAGE;
            }
        }
        super.installViews();

      //  if (mUrl.contains("index_")) {
            llBackContainer.setVisibility(View.VISIBLE);
        //}
    }

    @Override
    public void turnToOtherPage(String turnType, Map<String, String> params) {
        switch (turnType) {
            case AppWebViewClient.TYPE_OUT_APP:
                try {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(URLDecoder.decode(params.get("url"), "utf-8")));
                    this.startActivity(intent);
                } catch (ActivityNotFoundException e) {
                    ToastUtil.showMessage("No app found");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                break;
            case AppWebViewClient.TYPE_TEL:
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + params.get("tel")));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                break;
            case AppWebViewClient.TYPE_HOME_PAGE:
                //附近的人列表页/首页
                RouterMain.MainActivity();
                mHandler.postDelayed(() ->
                                RxBus.getDefault().post(new MainSwitchPageEvent(MainMenuContsant.MAIN_MENU_NEARBY)),
                        100);
                break;
            case AppWebViewClient.TYPE_FEADBACK:
                RouterMine.FeedbackActivity();
                break;
            case AppWebViewClient.TYPE_SET_PASSWORD:
                RouterMine.AccountSecurityActivity();
                break;
            default:
                openNewPage(turnType, new JSONObject());
                break;
        }
    }

    public void openNewPage(String eventName, JSONObject json) {
        switch (eventName) {
            //个人资料设置页
            case AppWebViewClient.TYPE_USERINFO_EDIT:
                RouterUser.PersonDetailEditActivity(RXingUtils.getUserId());
                break;
            //附近的人列表页/首页
            case AppWebViewClient.TYPE_HOME_PAGE:
                RouterMain.MainActivity();
                mHandler.postDelayed(() ->
                                RxBus.getDefault().post(new MainSwitchPageEvent(MainMenuContsant.MAIN_MENU_NEARBY)),
                        100);
                break;
            case AppWebViewClient.TYPE_SET_PASSWORD:
                RouterMine.AccountSecurityActivity();
                break;
            case AppWebViewClient.TYPE_FEADBACK:
                RouterMine.FeedbackActivity();
                break;
            case AppWebViewClient.TYPE_OPEN_PAGE:
                //turnToByARoute 是之前写的根据url路由 拆分参数 进行跳转的 旧版本残留
                //下面的是通过前端调用函数直接调用的 window.xys.routerJump , 加入了event事件
                UrlUtil.turnToARoutePage4JO(json);
                break;
            default:
                break;
        }
    }

    @Override
    public void turnToByARoute(String url) {
        if (StringUtils.isEmpty(url)) {
            return;
        }
        UrlUtil.turnToARoutePage(EncodeUtils.urlDecode(url));
    }

    @Override
    public String getUrl() {
        return mUrl;
    }

    @Override
    public String getHeadGson() {
        return mHeadGson;
    }

    @Override
    public boolean getCleanCookie() {
        return true;
    }

    @Override
    public int getStatusBarHeight() {
        return ViewUtils.getStatusBarHeight(mActivity);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            if (requestCode == AppWebChromeClient.FILE_CHOOSER_RESULT_CODE || requestCode == AppWebChromeClient.RECORD_VIDEO) {
                if (null == mUploadMessage && null == mUploadCallbackAboveL) {
                    return;
                }
                Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
                if (mUploadCallbackAboveL != null) {
                    onActivityResultAboveL(requestCode, resultCode, data);
                } else if (mUploadMessage != null) {
                    mUploadMessage.onReceiveValue(result);
                    mUploadMessage = null;
                }
            }
        } catch (Exception ignored) {

        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
        if ((requestCode == AppWebChromeClient.FILE_CHOOSER_RESULT_CODE
                || requestCode == AppWebChromeClient.RECORD_VIDEO)
                && mUploadCallbackAboveL != null) {
            Uri[] results = null;
            if (resultCode == RESULT_OK) {
                if (data != null) {
                    String dataString = data.getDataString();
                    ClipData clipData = data.getClipData();
                    if (clipData != null) {
                        results = new Uri[clipData.getItemCount()];
                        for (int i = 0; i < clipData.getItemCount(); i++) {
                            ClipData.Item item = clipData.getItemAt(i);
                            results[i] = item.getUri();
                        }
                    }
                    if (dataString != null) {
                        results = new Uri[]{Uri.parse(dataString)};
                    }
                }
            }
            mUploadCallbackAboveL.onReceiveValue(results);
            mUploadCallbackAboveL = null;
        }
    }
}